// pages/my-pages/top-up-add/index.js
const httpUtils = require('../../../utils/httpUtils')
const ui = require('../../../utils/ui')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    member: {},
    showMemberValue: null,
    disableRadio: true,
    noChecked: true,
    yesChecked: false,
    positionVisible: false,
    expenseItemValue: '请选择消费项目',
    itemList: [],
    voucher: {},
    usableNum: 0,
    usableNumValue: '',
    useDiscount: '0',
    addForm: {
      memberId: null,
      amount: null,
      giftPrice: null,
      discount: null,
      expenseItemId: null,
      isUseDiscount: false
    },
    baseItemList: [],
    checkStaffIndex: -1,
    user: {},
  },
  //查询消费项目列表
  getItemList: function (e) {
    let obj = {
      method: 'GET',
      showLoading: false,
      url: 'item/getItemPickerList'
    }
    httpUtils.request(obj).then(res => {
      console.log(res.data.message)
      if (res.data.retCode == 0) {
        this.setData({
          itemList: res.data.data
        })
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });
  },
  //处理代金券券信息
  handVoucherInfo: function () {
    console.log('开始执行代金券处理方法')
    let that = this;
    let voucher = that.data.voucher;
    console.log(!that.isEmptyObject(voucher))
    if (!that.isEmptyObject(voucher)) {
      that.setData({
        usableNumValue: voucher.voucherName,
        'addForm.vouMemId': voucher.id
      })
    }
  },
  //空对象判断
  isEmptyObject: function (obj) {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        return false;
      }
    }
    return true;
  },
  //打开消费项目下拉列表
  onItemPicker: function (e) {
    console.log('点击了消费项目选择')
    this.setData({
      positionVisible: true
    })
  },
  //消费项目弹窗点击确定按钮
  onPickerChange: function (e) {
    let that = this;
    let value = e.detail.value[0];
    let obj = {
      method: 'GET',
      showLoading: false,
      url: 'item/getItemById?id=' + value
    }
    httpUtils.request(obj).then(res => {
      console.log(res.data.message)
      if (res.data.retCode == 0) {
        let baseItemList = res.data.data.baseItemEntityList;
        this.setData({
          'addForm.amount': res.data.data.defaultPrice,
          expenseItemValue: res.data.data.itemName,
          baseItemList: baseItemList,
          usableNum: 0,
          'addForm.vouMemId': ''
        })
        this.queryVoucherList();
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });

    that.setData({
      'addForm.expenseItemId': value
    })
    if (null != that.data.expenseItemValue && that.data.expenseItemValue > 8) {
      this.setData({
        expenseItemValue: that.data.expenseItemValue.slice(0, 8)
      })
    }
  },
  //消费项目弹窗点击取消按钮
  onPickerCancel: function (e) {
    this.setData({
      positionVisible: false,
      item: {}
    })
  },
  //单选按钮改变
  handleRadioChange: function (e) {
    let radioValue = e.detail.value;
    this.setData({
      useDiscount: radioValue,
    });
    if ('0' == radioValue) {
      this.setData({
        noChecked: true,
        yesChecked: false,
      })
    } else {
      this.setData({
        noChecked: false,
        yesChecked: true,
      })
    }
  },
  //折扣信息变更
  inputDiscount: function (e) {
    let discount = e.detail.value;
    discount = discount.replace(/\D/g, '')
    if (null != discount && '' != discount && 100 < discount) {
      ui.showToast('折扣率不能大于100');
      discount = discount.slice(0, 2);
    }
    this.setData({
      'addForm.discount': discount
    })
  },
  //消费金额信息变更
  inputAmount: function (e) {
    let amount = e.detail.value;
    amount = amount.replace(/\D/g, '')
    if (null != amount && '' != amount && 99999999 < amount) {
      ui.showToast('金额不能大于99999999');
      amount = amount.slice(0, 8);
    }
    this.setData({
      'addForm.amount': amount
    })
  },
  //消费金额信息变更
  inputGiftAmount: function (e) {
    let giftPrice = e.detail.value;
    giftPrice = giftPrice.replace(/\D/g, '')
    if (null != giftPrice && '' != giftPrice && 99999999 < giftPrice) {
      ui.showToast('金额不能大于99999999');
      giftPrice = giftPrice.slice(0, 8);
    }
    this.setData({
      'addForm.giftPrice': giftPrice
    })
  },
  //点击了确定按钮
  confirmSaveButton: function (e) {
    console.log('点击了保存')
    if (this.data.useDiscount == '0') {
      this.setData({
        'addForm.isUseDiscount': false
      })
    } else {
      this.setData({
        'addForm.isUseDiscount': true
      })
    }
    let baseItemList = this.data.baseItemList;
    this.setData({
      'addForm.baseItemList': baseItemList
    });
    let obj = {
      method: 'POST',
      showLoading: true,
      url: 'expenseBill/addExpense',
      data: this.data.addForm
    }
    httpUtils.request(obj).then(res => {
      if (res.data.retCode == 0) {
        ui.showToast('保存成功')
        wx.navigateBack({
          detail: 1
        })
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });
  },
  //点击了会员列表
  checkMemberButton: function (e) {
    console.log('点击了会员列表')
    let that = this;
    that.setData({
      usableNum: 0,
      'addForm.vouMemId': ''
    })
    wx.navigateTo({
      url: '/pages/my-pages/select-member/index',
    })
  },
  //金额判断
  onPriceInput: function (e) {
    let defaultPrice = e.detail.value;
    defaultPrice = defaultPrice.replace(/\D/g, '')
    this.setData({
      'addForm.topUpPrice': defaultPrice
    })
  },
  //点击了店员列表
  checkStaffButton: function (e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      checkStaffIndex: index
    })
    console.log('点击了店员列表, index = ' + index)
    wx.navigateTo({
      url: '/pages/my-pages/select-staff/index',
    })
  },
  //更新项目列表中操作店员
  setBaseItemStaff() {
    let that = this;
    let index = that.data.checkStaffIndex;
    if (index != -1) {
      let user = that.data.user;
      that.setData({
        ['baseItemList[' + index + '].opeUser']: user,
        ['baseItemList[' + index + '].opeUserId']: user.id,
        ['baseItemList[' + index + '].opeUserName']: user.nickName
      })
    }
  },
  //查询会员可用代金券
  queryVoucherList: function () {
    let that = this;
    let memberId = that.data.addForm.memberId;
    let usableNum = that.data.usableNum;
    let itemId = that.data.addForm.expenseItemId;
    if (memberId != null && -1 != memberId && itemId != null && usableNum == 0) {
      //查询会员可用代金券集合
      let obj = {
        method: 'GET',
        showLoading: false,
        url: 'voucherMember/usableNum?memberId=' + memberId + '&itemId=' + itemId
      }
      httpUtils.request(obj).then(res => {
        if (res.data.retCode == 0) {
          that.setData({
            usableNum: res.data.data,
            usableNumValue: res.data.data + '张可用代金券'
          })
        } else {
          ui.showToast(res.data.message)
        }
      }).catch(err => {
        ui.showToast('请求失败')
      });
    }
  },
  //点击了查看代金券
  checkMemberVoucherButton: function (e) {
    console.log('点击了查看代金券')
    let that = this;
    let memberId = that.data.addForm.memberId;
    let itemId = that.data.addForm.expenseItemId;
    wx.navigateTo({
      url: '/pages/my-pages/member-voucher-list/index?memberId=' + memberId + '&itemId=' + itemId + '&checkFlag=true',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    let member = that.data.member
    if (member != null) {
      if (member.id != null && member.id != undefined) {
        that.setData({
          'addForm.memberId': member.id,
          'addForm.discount': member.discount,
          showMemberValue: member.memberName + ' (NO：' + member.memberNo + ')',
        })
      }
    }
    if (null == that.data.showMemberValue || undefined == that.data.showMemberValue) {
      that.setData({
        showMemberValue: '非会员 (NO：-1)',
        disableRadio: true
      })
    } else {
      that.setData({
        useDiscount: '1',
        disableRadio: false,
        noChecked: false,
        yesChecked: true
      })
    }
    if (that.data.showMemberValue.length > 11) {
      that.setData({
        showMemberValue: that.data.showMemberValue.slice(0, 11)
      })
    }
    that.getItemList();
    that.setBaseItemStaff();
    that.queryVoucherList();
    that.handVoucherInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})